#!/bin/bash
source tools/getenv.sh

# yum install -y supervisor
# systemctl daemon-reload  Systemd 会将 Unit 文件的内容写到缓存中，因此当 Unit 文件被更新时，需要告诉 Systemd 重新读取所有的 Unit 文件
# systemctl status test_stockgo_8080_autostart
# 需要在根目录下运行make xxx
if [[ "$env" == "test" || "$env" == "prod" ]]; then
    numbers=$(getPortFromRealConfigFile)
    echo "连续数字为：$numbers"
else
  echo -e "$BOLODGREEN $env 环境，不需要配置systemd$RESET"
  exit 0
fi



if [[ "$damonMode" == "supervisor" ]]; then
  which supervisorctl
  if [[ $? -ne 0 ]]; then
    echo -e "$RED 请安装supervisor $RESET"
    echo "yum install -y supervisor
systemctl enable supervisord # 开机自启动
systemctl start supervisord # 启动supervisord服务

systemctl status supervisord # 查看supervisord服务状态
ps -ef|grep supervisord # 查看是否存在supervisord进程
"
    exit 1
  fi
elif [[ "$damonMode" == "systemd" ]]; then
  echo -e "$RED 请编写systemd的检测脚本$RESET"
fi


# 判断配置文件中是否有同样的端口
port=$(getPortFromRealConfigFile)
echo -e "当前端口是： $GREEN $port $RESET"
echo "------------------------------"
echo "$LINK_FILE"
echo "------------------------------"

# shellcheck disable=SC2126
port_count=$(getPortCountFromConfigFile)
if [ "$port_count" -eq 1 ]; then
    echo -e "配置文件 $LINK_FILE $GREEN 中包含 port=$port 的行数:   $port_count $RESET"
else
    echo -e "$RED 当前目录中包含port=$port 的行数!=1，请检查配置文件，看是否创建错软连 $RESET"
    exit 1
fi

pidfile_count=$(getPidFIleCountFromConfigFile)
if [[ "$env" == "test" || "$env" == "prod" ]]; then
  if [ "$pidfile_count" -eq 1 ]; then
    echo -e "配置文件 $LINK_FILE $GREEN 中包含 pidfile=xxx${port}xxx 的行数:   $pidfile_count $RESET"
  else
    echo -e "$RED 当前目录中包含 中包含 pidfile=xxx${port}xxx 的行数!=1，请检查配置文件，看是否创建错软连 $RESET"
    exit 1
  fi
fi

# 服务名字

#systemctl status "${service_name}"

echo "---------------------------------"
echo "service_name:${service_name}"
#echo "service_file:${service_file}"
echo "real_config_file:${real_config_file}"
echo "current_dir:${current_dir}"
echo "app_name:${app_name}"
echo "APP_BIN_NAME:${APP_BIN_NAME}"
echo "---------------------------------"

# 环境不一样，supe的配置文件不一样

function getSupervisorServiceFile() {
    num=$(tail -1 /etc/supervisord.conf|grep -c "supervisord\.d\/\*\.ini")
    tail -1 /etc/supervisord.conf|grep  "supervisord\.d\/\*\.ini"
    echo "num:$num"
    if [[ "$num" == 1 ]]; then
      supervisor_service_conf="/etc/supervisord.d/"
      service_file="${supervisor_service_conf}${service_name}.ini"
      echo -e "$GREEN service_file:$service_file $RESET"
    else
      num=$(tail -1 /etc/supervisord.conf|grep -c "\/etc\/supervisor\/conf\.d\/\*\.conf")
      if [[ "$num" == 1 ]]; then
        echo "取默认配置，将要写入到文件:$service_file"
      else
        echo "和目前的都不匹配，请重新编写注册脚本"
      fi
    fi
}

function getSystemdServiceFile() {
    echo ""
}

function myRegisterSupervisorService() {
    chmod 755 "${current_dir}"/tools/autostart.sh

    if [ -f "$service_file" ]; then
        echo -e "$GREEN 服务文件已经存在,状态如下 $RESET"
        supervisorctlStatus
        exit 0
    else
      echo -e "$GREEN service_file:$service_file $RESET"
      echo -e "$RED 服务文件不存在，创建服务文件 $RESET "
# 我要用软连，在 Supervisor 的配置中，autostart.sh 脚本中的 current_dir="$PWD"
# 将始终获取实际目录的路径，而不是软链接目录的路径。为了在 Supervisor 配置中获取软链接目录的路径，
# 您可以通过传递软链接目录的路径作为环境变量的方式，在 autostart.sh 脚本中使用该环境变量。
      echo -e "$GREEN 执行命令...
------------------------------------------------------------------------------------------------------------ $RESET"
      echo "
echo [program:${service_name}]
command=${current_dir}/tools/autostart.sh
;process_name=%(program_name)s ; process_name expr (default %(program_name)s)
;numprocs=3                    ; number of processes copies to start (def 1)
directory=${current_dir}                ; directory to cwd to before exec (def no cwd)
environment=SUPERVISOR_CURRENT_DIR="${current_dir}"
;umask=022                     ; umask for process (default None)
;priority=999                  ; the relative start priority (default 999)
autostart=true                ; start at supervisord start (default: true)
;startsecs=1                   ; # of secs prog must stay up to be running (def. 1)
startretries=10000                ; max # of serial start failures when starting (default 3)
autorestart=true        ; when to restart if exited after running (def: unexpected)
;exitcodes=0,2                 ; 'expected' exit codes used with autorestart (default 0,2)
;stopsignal=QUIT               ; signal used to kill process (default TERM)
;stopwaitsecs=10               ; max num secs to wait b4 SIGKILL (default 10)
;stopasgroup=false             ; send stop signal to the UNIX process group (default false)
;killasgroup=false             ; SIGKILL the UNIX process group (def false)
user=root                  ; setuid to this UNIX account to run the program
;redirect_stderr=true          ; redirect proc stderr to stdout (default false)
stdout_logfile=/tmp/myangels-boost-handle.log        ; stdout log path, NONE for none; default AUTO
;stdout_logfile_maxbytes=1MB   ; max # logfile bytes b4 rotation (default 50MB)
;stdout_logfile_backups=10     ; # of stdout logfile backups (0 means none, default 10)
;stdout_capture_maxbytes=1MB   ; number of bytes in 'capturemode' (default 0)
;stdout_events_enabled=false   ; emit events on stdout writes (default false)
;stderr_logfile=/a/path        ; stderr log path, NONE for none; default AUTO
;stderr_logfile_maxbytes=1MB   ; max # logfile bytes b4 rotation (default 50MB)
;stderr_logfile_backups=10     ; # of stderr logfile backups (0 means none, default 10)
;stderr_capture_maxbytes=1MB   ; number of bytes in 'capturemode' (default 0)
;stderr_events_enabled=false   ; emit events on stderr writes (default false)
;environment=A=1,B=2       ; process environment additions (def no adds)
;serverurl=AUTO                ; override serverurl computation (childutils) >  $service_file"
echo -e "$GREEN ------------------------------------------------------------------------------------------------------------$RESET"

      echo "
[program:${service_name}]
command=${current_dir}/tools/autostart.sh
;process_name=%(program_name)s ; process_name expr (default %(program_name)s)
;numprocs=3                    ; number of processes copies to start (def 1)
directory=${current_dir}                ; directory to cwd to before exec (def no cwd)
environment=SUPERVISOR_CURRENT_DIR=\"${current_dir}\"
;umask=022                     ; umask for process (default None)
;priority=999                  ; the relative start priority (default 999)
autostart=true                ; start at supervisord start (default: true)
;startsecs=1                   ; # of secs prog must stay up to be running (def. 1)
startretries=5                ; max # of serial start failures when starting (default 3)
autorestart=true        ; when to restart if exited after running (def: unexpected)
;exitcodes=0,2                 ; 'expected' exit codes used with autorestart (default 0,2)
;stopsignal=QUIT               ; signal used to kill process (default TERM)
;stopwaitsecs=10               ; max num secs to wait b4 SIGKILL (default 10)
;stopasgroup=false             ; send stop signal to the UNIX process group (default false)
;killasgroup=false             ; SIGKILL the UNIX process group (def false)
user=root                  ; setuid to this UNIX account to run the program
;redirect_stderr=true          ; redirect proc stderr to stdout (default false)
stdout_logfile=/tmp/myangels-boost-handle.log        ; stdout log path, NONE for none; default AUTO
;stdout_logfile_maxbytes=1MB   ; max # logfile bytes b4 rotation (default 50MB)
;stdout_logfile_backups=10     ; # of stdout logfile backups (0 means none, default 10)
;stdout_capture_maxbytes=1MB   ; number of bytes in 'capturemode' (default 0)
;stdout_events_enabled=false   ; emit events on stdout writes (default false)
;stderr_logfile=/a/path        ; stderr log path, NONE for none; default AUTO
;stderr_logfile_maxbytes=1MB   ; max # logfile bytes b4 rotation (default 50MB)
;stderr_logfile_backups=10     ; # of stderr logfile backups (0 means none, default 10)
;stderr_capture_maxbytes=1MB   ; number of bytes in 'capturemode' (default 0)
;stderr_events_enabled=false   ; emit events on stderr writes (default false)
;environment=A=1,B=2       ; process environment additions (def no adds)
;serverurl=AUTO                ; override serverurl computation (childutils)" > "$service_file"
      supervisorctl reread
      supervisorctl update
      supervisorctl start "${service_name}"
      supervisorctlStatus
    fi
}

function myRegisterSystemdService() {
    chmod 755 "${current_dir}"/tools/autostart.sh

    if [ -f "$service_file" ]; then
        echo -e "$GREEN 服务文件已经存在,状态如下 $RESET"
        systemctl status "${service_name}"
        exit 0
    else
      echo -e "$RED 服务文件不存在，创建服务文件 $RESET "
      echo "
      [Unit]
      Description=${service_name}.autoStart
      After=network.target

      [Service]
      Type=simple
      Restart=always
      RestartSec=3
      StartLimitInterval=0
      WorkingDirectory=${current_dir}
      ExecStart=${current_dir}/tools/autostart.sh &

      [Install]
      WantedBy=multi-user.target
      "
      echo " >  $service_file "
      echo "
        [Unit]
        Description=${service_name}.autoStart
        After=network.target

        [Service]
        Type=simple
        Restart=always
        RestartSec=3
        StartLimitInterval=0
        WorkingDirectory=${current_dir}
        ExecStart=${current_dir}/tools/autostart.sh &

        [Install]
        WantedBy=multi-user.target
        " > "$service_file"
        systemctl enable "${service_name}"
        systemctl start "${service_name}"
        systemctl list-units --type=service | grep "${service_name}"
        systemctl status "${service_name}"

        # systemctl restart "${service_name}"
    fi
}

if [[ "$damonMode" == "supervisor" ]]; then
  getSupervisorServiceFile
  myRegisterSupervisorService
elif [[ "$damonMode" == "systemd" ]]; then
  getSystemdServiceFile
  myRegisterSystemdService
fi


